/*
 * Copyright (c) 2008 Benoit Bouchez, Nicolas Giard
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.noocodecommit.wicket.stuff.jquery.plugin.ui.autocomplete;

import java.util.Iterator;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.repeater.data.ListDataProvider;

import com.noocodecommit.wicket.stuff.jquery.JQCore;
import com.noocodecommit.wicket.stuff.jquery.JQOptions;
import com.noocodecommit.wicket.stuff.jquery.exception.CannotApplyJQOptionException;
import com.noocodecommit.wicket.stuff.jquery.plugin.IJQPluginComponent;
import com.noocodecommit.wicket.stuff.jquery.plugin.JQPlugin;

/**
 * @author Nicolas Giard
 */
public class JQAutocomplete extends WebMarkupContainer implements IJQPluginComponent
{
	/** JQuery plugin */
	private JQAutocompletePlugin plugin;

	/** JQuery default options */
	private JQAutocompleteOptions options = new JQAutocompleteOptions();

	/** Data container */
	private TextField parent;

	/** */
	private ListDataProvider dataProvider;

	/**
	 * @param id
	 * @param key
	 * @param parent
	 * @param dataProvider
	 */
	public JQAutocomplete(String id, String key, TextField parent, ListDataProvider dataProvider)
	{
		super(id);
		this.parent = parent;
		this.dataProvider = dataProvider;
		this.setOutputMarkupId(true);
		if (key == null)
		{
			key = JQAutocompletePlugin.DEFAULT_KEY;
		}
		if (JQCore.get().getPlugin(key) == null)
		{
			new JQAutocompletePlugin(key);
		}
		this.plugin = (JQAutocompletePlugin) JQCore.get().getPlugin(key);

		JQCore.get().getPlugin(plugin.getKey()).attachComponentForDocumentReady(this);
	}

	/**
	 * Constructor
	 * 
	 * @param id
	 * @param parent
	 * @param dataProvider
	 */
	public JQAutocomplete(String id, TextField parent, ListDataProvider dataProvider)
	{
		this(id, null, parent, dataProvider);
	}

	public JQAutocompleteOptions getOptions()
	{
		return options;
	}

	public void setOptions(JQOptions options)
	{
		if (options.getClass().equals(JQAutocompleteOptions.class))
		{
			this.options = (JQAutocompleteOptions) options;
		}
		else
		{
			throw new CannotApplyJQOptionException(JQAutocomplete.class, options.getClass(), JQAutocompleteOptions.class);
		}
	}

	public JQAutocompletePlugin getPlugin()
	{
		return plugin;
	}

	public void setPlugin(JQPlugin plugin)
	{
		this.plugin = (JQAutocompletePlugin) plugin;
	}

	@SuppressWarnings("unchecked")
	public String getWidgetReadyScript(boolean reset)
	{
		// return "$('#" + this.getMarkupId() + "')." + (reset ? "autocomplete('destroy')." : "") + options.getDocumentReadyOptions();

		StringBuffer sb = new StringBuffer();
		sb.append("{data: [");
		Iterator<String> iter = dataProvider.iterator(0, dataProvider.size());
		String separator = "";
		while (iter.hasNext())
		{
			sb.append(separator + " \"" + iter.next() + "\"");
			separator = ",";
		}
		sb.append("]}");

		return "$('#" + parent.getMarkupId() + "').autocomplete(" + sb.toString() + ");";
	}

	public String getAfterAjaxUpdateScript()
	{
		// return "$('#" + this.getMarkupId() + "')." + options.getDocumentReadyOptions();
		return "$('#" + parent.getMarkupId() + "').autocomplete({data: [\"aero\", \"airplane\", \"book\", \"movie\", \"music\", \"sports\", \"skating\", \"swim\"]});";
	}

	/**
	 * Activate the accordion item<br>
	 * Appends a javascript call <code>$('#id').autocomplete('activate', match)</code> to the ajax target.
	 * 
	 * @param match
	 *            Activate the first element matching the given expression
	 * @param target
	 *            Ajax target
	 */
	public void activate(String match, AjaxRequestTarget target)
	{
		target.appendJavascript("$('#" + parent.getMarkupId() + "').autocomplete('activate', " + match + ")");
	}

	/**
	 * Activate the accordion item<br>
	 * Appends a javascript call <code>$('#id').autocomplete('activate', index)</code> to the ajax target.
	 * 
	 * @param index
	 *            element index
	 * @param target
	 *            Ajax target
	 */
	public void activate(AjaxRequestTarget target, Integer index)
	{
		target.appendJavascript("$('#" + parent.getMarkupId() + "').autocomplete('activate', " + index.toString() + ")");
	}

	/**
	 * Activate the accordion item<br>
	 * Appends a javascript call <code>$('#id').autocomplete('activate', true|false)</code> to the ajax target.
	 * 
	 * @param open
	 *            false to close all parts of autocomplete, true to open all parts
	 * @param target
	 *            Ajax target
	 */
	public void activate(AjaxRequestTarget target, boolean open)
	{
		target.appendJavascript("$('#" + parent.getMarkupId() + "').autocomplete('activate', " + open + ")");
	}

	/**
	 * Enable the accordion<br>
	 * Appends a javascript call <code>$('#id').autocomplete('enable')</code> to the ajax target.
	 * 
	 * @param target
	 *            Ajax target
	 */
	public void enable(AjaxRequestTarget target)
	{
		target.appendJavascript("$('#" + parent.getMarkupId() + "').autocomplete('enable')");
	}

	/**
	 * Disable the accordion<br>
	 * Appends a javascript call <code>$('#id').autocomplete('disable')</code> to the ajax target.
	 * 
	 * @param target
	 *            Ajax target
	 */
	public void disable(AjaxRequestTarget target)
	{
		target.appendJavascript("$('#" + parent.getMarkupId() + "').autocomplete('disable')");
	}

	/**
	 * Destroy the accordion<br>
	 * Appends a javascript call <code>$('#id').autocomplete('destroy')</code> to the ajax target.
	 * 
	 * @param target
	 *            Ajax target
	 */
	public void destroy(AjaxRequestTarget target)
	{
		target.appendJavascript("$('#" + parent.getMarkupId() + "').autocomplete('destroy')");
	}
}